<template>
  <div class="form-page">
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">表单管理</h1>
        <p class="page-subtitle">管理系统中的所有表单模板</p>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="goToFormDesigner">
          <el-icon><Plus /></el-icon>
          创建表单
        </el-button>
        <el-button>
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="search-section">
      <div class="search-left">
        <el-input
          v-model="searchQuery"
          placeholder="搜索表单名称..."
          prefix-icon="Search"
          style="width: 300px"
          clearable
          @input="handleSearch"
        />
        <el-select v-model="statusFilter" placeholder="状态筛选" style="width: 150px" @change="handleSearch">
          <el-option label="全部" :value="null" />
          <el-option label="启用" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
      </div>
      <div class="search-right">
        <el-button @click="handleRefresh">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 表单列表 -->
    <div class="forms-content">
      <el-table
        v-loading="loading"
        :data="formList"
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="formName" label="表单名称" min-width="150">
          <template #default="{ row }">
            <div class="form-name">
              <span class="name">{{ row.formName }}</span>
              <span class="description" v-if="row.formDescription">{{ row.formDescription }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'info'">
              {{ row.statusDesc }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createBy" label="创建者" width="120" />
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240" fixed="right">
          <template #default="{ row }">
            <div class="table-actions">
              <el-button type="primary" link @click="handleEdit(row)">
                <el-icon class="el-icon--left"><Edit /></el-icon>
                编辑
              </el-button>
              <el-button
                :type="row.status === 1 ? 'warning' : 'success'"
                link
                @click="handleToggleStatus(row)"
              >
                <el-icon class="el-icon--left"><Switch /></el-icon>
                {{ row.status === 1 ? '禁用' : '启用' }}
              </el-button>
              <el-button type="danger" link @click="handleDelete(row)">
                <el-icon class="el-icon--left"><Delete /></el-icon>
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          background
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>


  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Download, Search, Refresh, Edit, Switch, Delete } from '@element-plus/icons-vue'
import { formApi } from '@/api'

// 响应式数据
const loading = ref(false)
const formList = ref<any[]>([])
const selectedForms = ref<any[]>([])
const searchQuery = ref('')
const statusFilter = ref<number | null>(null)

// 分页数据
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})


// 获取表单列表
const getFormList = async () => {
  loading.value = true
  try {
    const params = {
      current: pagination.current,
      size: pagination.size,
      formName: searchQuery.value || undefined,
      status: statusFilter.value
    }
    const response = await formApi.getFormList(params)
    // 响应拦截器已经处理了状态码，直接使用返回的数据
    formList.value = response.data.records
    pagination.total = response.data.total
  } catch (error) {
    console.error('获取表单列表失败:', error)
    ElMessage.error('获取表单列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  pagination.current = 1
  getFormList()
}

// 刷新
const handleRefresh = () => {
  searchQuery.value = ''
  statusFilter.value = null
  pagination.current = 1
  getFormList()
}

// 跳转到表单设计器
const goToFormDesigner = () => {
  window.location.href = '/home/form/design'
}

// 分页处理
const handleSizeChange = (val: number) => {
  pagination.size = val
  getFormList()
}

const handleCurrentChange = (val: number) => {
  pagination.current = val
  getFormList()
}

// 选择处理
const handleSelectionChange = (val: any[]) => {
  selectedForms.value = val
}


// 编辑表单 - 跳转到表单设计器并传递表单ID
const handleEdit = (row: any) => {
  window.location.href = `/home/form/design?id=${row.id}`
}

// 切换状态
const handleToggleStatus = async (row: any) => {
  const newStatus = row.status === 1 ? 0 : 1
  const statusText = newStatus === 1 ? '启用' : '禁用'
  
  try {
    await ElMessageBox.confirm(
      `确定要${statusText}表单"${row.formName}"吗？`,
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await formApi.changeFormStatus(row.id, newStatus)
    // 响应拦截器已经处理了状态码，直接显示成功信息
    ElMessage.success(`${statusText}成功`)
    getFormList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error(`${statusText}表单失败:`, error)
      ElMessage.error(`${statusText}失败`)
    }
  }
}

// 删除表单
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除表单"${row.formName}"吗？此操作不可恢复！`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await formApi.deleteForm(row.id)
    // 响应拦截器已经处理了状态码，直接显示成功信息
    ElMessage.success('删除成功')
    getFormList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除表单失败:', error)
      ElMessage.error('删除失败')
    }
  }
}



// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 页面挂载时获取数据
onMounted(() => {
  getFormList()
})
</script>

<style scoped lang="scss">
.form-page {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

  .header-content {
    .page-title {
      margin: 0;
      font-size: 24px;
      color: #333;
    }

    .page-subtitle {
      margin: 5px 0 0 0;
      color: #666;
      font-size: 14px;
    }
  }

  .header-actions {
    display: flex;
    gap: 12px;
  }
}

.search-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

  .search-left {
    display: flex;
    gap: 12px;
    align-items: center;
  }

  .search-right {
    display: flex;
    gap: 12px;
  }
}

.forms-content {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 20px;

  .form-name {
    .name {
      font-weight: 500;
      color: #333;
    }

    .description {
      display: block;
      font-size: 12px;
      color: #999;
      margin-top: 4px;
    }
  }

  .table-actions {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
  }

  .pagination-wrapper {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }
}


</style>
